package reduce.fz.com.reduce.custom.delegate;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by chenming on 2015/7/10 0010.
 */
public class RecyclerViewDelegate implements ViewDelegate{

    private final int[] mViewLocationResult = new int[2];
    private final Rect mRect = new Rect();

    public boolean isViewBeingDragged(MotionEvent event, RecyclerView view) {
        try {
            if (view.getAdapter() == null || view.getAdapter().getItemCount() <= 0) {
                return true;
            }
            view.getLocationOnScreen(mViewLocationResult);
            final int viewLeft = mViewLocationResult[0], viewTop = mViewLocationResult[1];
            mRect.set(viewLeft, viewTop, viewLeft + view.getWidth(), viewTop + view.getHeight());
            final int rawX = (int) event.getRawX(), rawY = (int) event.getRawY();

            if (mRect.contains(rawX, rawY)) {
                return isReadyForPull(view, rawX - mRect.left, rawY - mRect.top);
            }

            return false;
        }catch (Throwable e){
            return false;
        }
    }

    @Override
    public boolean isReadyForPull(View view, final float x, final float y) {
        boolean ready = false;

        // First we check whether we're scrolled to the top
        RecyclerView absListView = (RecyclerView) view;
        RecyclerView.Adapter adapter = absListView.getAdapter();
        if (adapter.getItemCount() == 0) {
            ready = true;
        } else {
            final View firstVisibleChild = absListView.getChildAt(0);
            ready = firstVisibleChild != null
                    && firstVisibleChild.getTop() >= absListView.getPaddingTop();
        }

        return ready;
    }
}
